<?php

class Epicentr extends Controller {
	protected $current_module = "epicentr";
	protected $ajax = false;
	protected $permissions = null;
	
	
	public function Epicentr($requirelogin = true) {
		parent::Controller();
		
		$this->load->model('companiesmodel');
		
		// first thing we need to do is determine if the application has been set up
		$mycompany = $this->companiesmodel->getMyCompany();
		
		if (!$mycompany) redirect('setup');
		
		$this->load->helper('image_helper');
		$this->load->library('authentication');
		$this->load->library('typography');
		
		
		
		//set up display parameters
		$this->layout->resetTheme('epicentr');

		$this->view_data['page_css'] = array('reset', 'ui.datepicker', 'screen', 'main', array('ie7' => 'ie7'), array('ie6' => 'ie6'));
		$this->view_data['page_js'] = array('jquery-1.2.6.pack', 
'jquery.hoverIntent-r5-min', 'jquery.multifile.pack', 'jquery.color', 'local_init', 'forms', 'jquery.inplace', 'companies_inplace');

		//load up any status messages
		$this->view_data['flashmessage'] = $this->db_session->flashdata('flashmessage');
		$this->view_data['flasherror'] = $this->db_session->flashdata('flasherror');

		//is this request via ajax?
		$this->ajax = $this->input->post('ajax');
		$this->view_data['ajax'] = $this->ajax;


		//----- refactoring below here


		//clients should only see the epicentr tab
		if ($this->authentication->getProfileType() == 'client') $this->view_data['maintab'] = 'mycompany';
		else $this->view_data['maintab'] = 'projects';
		
		$this->view_data['loggedInUser'] = $this->authentication->getUserFullName();
		
		if ($this->authentication->getProfileType() != 'client') {		
			$this->view_data['modules'] = array('Clients' => site_URL('companies/clients'),
												'Prospects' => site_URL('companies/prospects'),
												'Suppliers' => site_URL('companies/suppliers'));
		} else $this->view_data['modules'] = false;
		
		
		$this->load->model('companiesmodel');	
		
		if ($this->authentication->getProfileType() == 'client') {
			$this->load->model('contactmodel');
			
			$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
			$mycompany = $this->contactmodel->getCurrentCompany($contact->id);
		} else 	$mycompany = $this->companiesmodel->getMyCompany();
		
		if ($mycompany) $this->view_data['page_title'] = $mycompany->company_name.' &middot; epicentr';
		else $this->view_data['page_title'] = 'epicentr';
		
		$this->view_data['mycompany'] = $mycompany;
		
		if ($this->authentication->getProfileType() == 'admin') {	
			if ($mycompany) $this->view_data['modules'][$mycompany->company_name] = site_URL('yourcompany');
			else $this->view_data['modules']['Admin'] = site_URL('yourcompany');
		}

		
		switch ($this->authentication->getProfileType()) {
			case 'admin':
				$this->permissions->editjob = true;
				$this->permissions->createinvoice = true;
				$this->permissions->assignusers = true;
				$this->permissions->archivejobs = true;
				$this->permissions->specifyhours = true;
				$this->permissions->specifybillable = true;
				$this->permissions->editcompanydetails = true;
				$this->permissions->viewcompanydetails = true;
				$this->permissions->publiccommentsonly = false;
				$this->permissions->seereporting = true;
				$this->permissions->selectdepartmentonupdate = true;
				$this->permissions->selecttaskonupdate = true;
				$this->permissions->makepublicupdates = true;
				$this->permissions->showupdatetime = true;
				$this->permissions->seearchive = true;
				$this->permissions->seeprojectstab = true;
				$this->permissions->seemycompanytab = false;
				$this->permissions->edittimesheets = true;
				$this->permissions->forcepublicupdates = false;
			break;
			case 'standard':
				$this->permissions->editjob = false;
				$this->permissions->createinvoice = false;
				$this->permissions->assignusers = false;
				$this->permissions->archivejobs = false;
				$this->permissions->specifyhours = true;
				$this->permissions->specifybillable = true;
				$this->permissions->editcompanydetails = false;
				$this->permissions->viewcompanydetails = true;
				$this->permissions->publiccommentsonly = false;
				$this->permissions->seereporting = false;
				$this->permissions->selectdepartmentonupdate = true;
				$this->permissions->selecttaskonupdate = true;
				$this->permissions->makepublicupdates = true;
				$this->permissions->showupdatetime = true;
				$this->permissions->seearchive = true;
				$this->permissions->seeprojectstab = true;
				$this->permissions->seemycompanytab = false;
				$this->permissions->edittimesheets = true;
				$this->permissions->forcepublicupdates = false;
			break;
			default:
				$this->permissions->editjob = false;
				$this->permissions->createinvoice = false;
				$this->permissions->assignusers = false;
				$this->permissions->archivejobs = false;
				$this->permissions->specifyhours = false;
				$this->permissions->specifybillable = false;
				$this->permissions->editcompanydetails = false;
				$this->permissions->viewcompanydetails = false;
				$this->permissions->publiccommentsonly = true;
				$this->permissions->seereporting = false;
				$this->permissions->selectdepartmentonupdate = false;
				$this->permissions->selecttaskonupdate = false;
				$this->permissions->makepublicupdates = false;
				$this->permissions->showupdatetime = false;
				$this->permissions->seearchive = false;
				$this->permissions->seeprojectstab = false;
				$this->permissions->seemycompanytab = true;
				$this->permissions->edittimesheets = false;
				$this->permissions->forcepublicupdates = true;
			break;
		}
		
		$this->view_data['permissions'] =& $this->permissions;
		
		if ($requirelogin) {
			$this->db_session->set_userdata('target_url', $this->uri->uri_string());
			$this->_checkAuthentication();
		}
		
	}
	
	public function index() {
		$this->load->model('jobsmodel');
		$this->load->model('timesheetmodel');
		$this->load->model('deadlinemodel');
		$this->load->model('filesmodel');
		$this->load->model('timesheetmodel'); 
		$this->load->model('activitymodel'); 
		
		$this->view_data['page_js'][] = 'home';
		$this->view_data['maintab'] = 'home';
		
		/*whats coming up stuff*/
		$comingfrom = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d"), date("Y")));
		$comingto = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") + 14, date("Y")));
		
		if ($this->authentication->getProfileType() == 'client') {
			$this->load->model('contactmodel');
			
			$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
			$company = $this->contactmodel->getCurrentCompany($contact->id);
			
			$comingup = $this->activitymodel->whatsComingUp(false, false, $comingfrom, $comingto, $company->id);
			
		} else $comingup = $this->activitymodel->whatsComingUp(false, $this->authentication->getuserId(), $comingfrom, $comingto);
		
		$this->view_data['comingup'] = $comingup;
		
		$cominguplist = $this->load->view('epicentr/content/timesheets/whatscomingup', $this->view_data, true);
		$this->view_data['cominguplist'] = $cominguplist;


		/*whats going on stuff*/
		$goingfrom = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 13, date("Y")));
		$goingto = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d"), date("Y")));
		
		if ($this->authentication->getProfileType() == 'client') {
			$this->load->model('contactmodel');
			
			$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
			$company = $this->contactmodel->getCurrentCompany($contact->id);
			
			$goingon = $this->timesheetmodel->whatsGoingOn(false, false, $goingfrom, $goingto, false, $company->id, true);
			
		} else $goingon = $this->timesheetmodel->whatsGoingOn(false, $this->authentication->getUserId(), $goingfrom, $goingto, true);
		
		if ($goingon) {    	
			foreach($goingon as $key => $update) {
				$goingon[$key]->files = $this->filesmodel->find( array('jobid' => $update->jobid, 'timesheetid' => $update->id), null, null, 'title ASC' );
			}
    	}
		
		$goingonlist = $this->load->view('epicentr/content/timesheets/whatsgoingon', array('updates' => $goingon), true);
		$this->view_data['goingonlist'] = $goingonlist;

		//get incomplete deadlines / milestone / tasks past my date
		$missedComingUp = $this->activitymodel->missedComingUp(false, $this->authentication->getUserId());
		$this->view_data['missedcomingup'] = $missedComingUp;


		$this->view_data['page_title'] = 'Whats Going On? &middot; ' . $this->view_data['page_title'];

		$this->layout->buildPage('main/home', $this->view_data);
    }
    
    public function projects() {
		$this->load->model('jobsmodel');
		$this->load->model('costcentermodel');

		if ($this->authentication->getProfileType() == 'client') {
			$this->load->model('contactmodel');
			
			$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
			$company = $this->contactmodel->getCurrentCompany($contact->id);
			
			if ($company) redirect('companies/view/'.$company->id);
			else redirect('');
		}


		$this->view_data['page_js'][] = 'projects';
		$this->view_data['page_js'][] = 'timesheet';
		$this->view_data['maintab'] = 'projects';
		
		
		
		$sticky_jobs = array();
		
		if ($this->authentication->getProfileType() == 'client') {
			$this->load->model('contactmodel');
			
			$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
			$company = $this->contactmodel->getCurrentCompany($contact->id);
			
			$fulljobslist = $this->jobsmodel->getCompanyJobs($company->id, $this->authentication->getUserId(), 1);
			
		} else $fulljobslist = $this->jobsmodel->getAssignedTo($this->authentication->getUserId(), 1);


		$assigned_jobs = $fulljobslist;

		//calculate completion % for each job and seperate sticky jobs
    	if($assigned_jobs) {
    		foreach($assigned_jobs as $key => $job) {
    			$assigned_jobs[$key]->completion = $this->jobsmodel->getCompletion($job->jobid);
    			
    			if (is_numeric($job->sticky)) {
    				$sticky_jobs[] = $job;
    				unset($assigned_jobs[$key]);
    			} else if ($job->cancelled || $job->archived) {
    				unset($assigned_jobs[$key]);
    			}
    		}
    	}
    	
    	if($fulljobslist) {
			foreach($fulljobslist as $key => $job) {
				$departments = $this->costcentermodel->getCostCentersForJob($job->jobid);
				$fulljobslist[$key]->departments = $departments;
				
				$jobtasks = $this->costcentermodel->getActivitiesForJob($job->jobid, true);
				
				$fulljobslist[$key]->tasks = $jobtasks;
				
				if ($departments) {		
					foreach($departments as $depkey => $department) {
						$tasks = $this->costcentermodel->getActivitiesForCostCenter($department->id);
						$fulljobslist[$key]->departments[$depkey]->tasks = $tasks;
					}
				}
			}
		}
		
		$this->view_data['assigned_jobs'] = $assigned_jobs;
		$this->view_data['sticky_jobs'] = $sticky_jobs;
		$this->view_data['fulljobslist'] = $fulljobslist;
		
		$this->layout->buildPage('main/projects', $this->view_data);
    }
    
    public function sticky() {
    	$this->load->model('jobsmodel');
    	
    	$action = $this->input->post('action', true);
    	$jobid = $this->input->post('jobid', true);
    	
    	switch ($action) {
    		case "stick":
    			$this->jobsmodel->stick($this->authentication->getUserId(), $jobid);
    		break;
    		case "unstick":
    			$this->jobsmodel->unstick($this->authentication->getUserId(), $jobid);
    		break;
    	}
    	
    	echo true;die();
    }
    
    public function whatsGoingOn($format = 'html') {
    	$this->load->model('timesheetmodel');
    	
    	$jobid = $this->input->post('jobid', true);
    	$startdate = $this->input->post('startdate', true);
    	$enddate = $this->input->post('enddate', true); 	
    	
    	if ($jobid) {
    	
    		$when = $this->input->post('when', true);
    	
			switch ($when) {
				case "today":
					$from = date('Y-m-d 00:00:00');
					$to = date('Y-m-d 23:59:59');
				break;
				case "yesterday":
					$from = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")));
					$to = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")));
				break;
				case "thisweek":
					$from = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 9, date("Y")));
					$to = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") - 2, date("Y")));
				break;
				case "thismonth":
					$from = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 31, date("Y")));
					$to = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") - 9, date("Y")));
				break;
			}
			
			$updates = $this->timesheetmodel->whatsGoingOn($jobid, $this->authentication->getUserId(), $from, $to);
			
    	} else if($startdate && $enddate) {
    		$from = date('Y-m-d 00:00:00', strtotime($startdate) );
			$to = date('Y-m-d 23:59:59', strtotime($enddate) );
		
			if ($this->authentication->getProfileType() == 'client') {
				$this->load->model('contactmodel');
				
				$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
				$company = $this->contactmodel->getCurrentCompany($contact->id);
				
				$updates = $this->timesheetmodel->whatsGoingOn(false, false, $from, $to, false, $company->id, true);
			
			} else $updates = $this->timesheetmodel->whatsGoingOn(false, $this->authentication->getUserId(), $from, $to, true);
			
    	} else {
    		$goingfrom = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 13, date("Y")));
			$goingto = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d"), date("Y")));
    		
    		$updates = $this->timesheetmodel->whatsGoingOn(false, $this->authentication->getUserId(), $goingfrom, $goingto);
    	}
    	
    	
    	   	
		switch ($format) {
			case "rss":
				$this->view_data['updates'] = $updates;
				$updatelist = $this->load->view('epicentr/content/timesheets/whatsgoingon-rss', $this->view_data, true);				
			break;
			case "html":
			default:
				$this->load->model('filesmodel');
				
				if ($updates) {    	
					foreach($updates as $key => $update) {
						$updates[$key]->files = $this->filesmodel->find( array('jobid' => $update->jobid, 'timesheetid' => $update->id), null, null, 'title ASC' );
					}
				}
				$this->view_data['updates'] = $updates;
				$updatelist = $this->load->view('epicentr/content/timesheets/whatsgoingon', $this->view_data, true);
			break;
		}
		
		if ( strlen($updatelist) ) echo $updatelist;
		else echo 0;
			
    	die();
    }
    
    public function whatsComingUp($format = 'html') {
    	/*whats coming up stuff*/
		$this->load->model('activitymodel');  
		
		$startdate = $this->input->post('startdate');
		$enddate = $this->input->post('enddate');
		
		if ($startdate && $enddate) {		
			$comingfrom = date('Y-m-d 00:00:00', strtotime($startdate) );
			$comingto = date('Y-m-d 23:59:59', strtotime($enddate) );
		} else {
			$comingfrom = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d"), date("Y")));
			$comingto = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") + 14, date("Y")));
		}
		
		$comingup = $this->activitymodel->whatsComingUp(false, $this->authentication->getUserId(), $comingfrom, $comingto);
		
		switch ($format) {
			case "rss":
				$cominguplist = $this->load->view('epicentr/content/timesheets/whatscomingup-rss', array('comingup' => $comingup), true);
				
			break;
			case "ical":
				$this->load->library('ciicalcreator');
				
				$this->ciicalcreator->setConfig( 'unique_id', 'atthefoundry.net' ); // set Your unique id
				$this->ciicalcreator->setProperty( 'method', 'PUBLISH' );
				
				foreach($comingup as $event) {
				
					$vevent = new vevent(); // create an event calendar component
					$vevent->setProperty( 'dtstart', array( 'year'=>2008, 'month'=>5, 'day'=>31, 'hour'=>19, 'min'=>0,  'sec'=>0 ));
					$vevent->setProperty( 'dtend',  array( 'year'=>2008, 'month'=>5, 'day'=>31, 'hour'=>22, 'min'=>30, 'sec'=>0 ));
					$vevent->setProperty( 'LOCATION', 'Central Placa' ); // property name - case independent
					$vevent->setProperty( 'summary', 'PHP summit' );
					$vevent->setProperty( 'description', 'This is a description' );
					$vevent->setProperty( 'comment', 'This is a comment' );
					$vevent->setProperty( 'attendee', 'attendee1@icaldomain.net' );
					
					$this->ciicalcreator->setComponent ( $vevent );
				
				}
				$this->ciicalcreator->returnCalendar();
				echo 'a';
				die();
			break;
			case "html":
			default:
				$cominguplist = $this->load->view('epicentr/content/timesheets/whatscomingup', array('comingup' => $comingup), true);
			break;
		}
		
		echo $cominguplist;die();
    }

	public function whatsGoingOnCount() {
		$this->load->model('jobsmodel');
    	$this->load->model('timesheetmodel');
    	
    	$jobid = $this->input->post('jobid', true);	
    	
    	
    	if (!$jobid) redirect('');
    	
    	$returndata = null;
    	
    	foreach ( array('today', 'yesterday', 'thisweek', 'thismonth') as $when) {
    	
			switch ($when) {
				case "today":
					$from = date('Y-m-d 00:00:00');
					$to = date('Y-m-d 23:59:59');
				break;
				case "yesterday":
					$from = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")));
					$to = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")));
				break;
				case "thisweek":
					$from = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 9, date("Y")));
					$to = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") - 2, date("Y")));
				break;
				case "thismonth":
					$from = date('Y-m-d 00:00:00', mktime(0, 0, 0, date("m") , date("d") - 31, date("Y")));
					$to = date('Y-m-d 23:59:59', mktime(0, 0, 0, date("m") , date("d") - 9, date("Y")));
				break;
			}
			
			$updates = $this->timesheetmodel->whatsGoingOn($jobid, $this->authentication->getUserId(), $from, $to);
			
			if ($updates) $returndata->$when = count($updates);
			else $returndata->$when = 0;
			
		}

		include ('Zend/Json.php');
    	
    	echo Zend_Json::encode($returndata);
    	exit();
    				
    	die();
    }

    public function quickSearch() {
		$this->load->model('companiesmodel');
		
		$searchterm = $this->input->post('searchterm');
		
		//make sure we dont get stuck on this page...
		if ($searchterm === false && $_REQUEST['X-Requested-With'] !== 'XMLHttpRequest') redirect('');
		
		if ($this->authentication->getProfileType() == 'client') {
			$this->load->model('contactmodel');
			
			$contact = $this->contactmodel->retrieve_by_field('email1', $this->authentication->getUserEmailaddress() );
			$mycompany = $this->contactmodel->getCurrentCompany($contact->id);
			$companylimiter = $mycompany->id;
		} else $companylimiter = false;
		
		
		if ($searchterm) {
			$searchParts = explode(' ', $searchterm);
			
			if ( count($searchParts) > 1) $returndata = $this->companiesmodel->quickSearch($searchParts, false, $companylimiter);
			else $returndata = $this->companiesmodel->quickSearch($searchterm, false, $companylimiter);
			
		} else {
			$returndata = false;
		}
		
		include ('Zend/Json.php');
    	
    	echo Zend_Json::encode($returndata);
    	exit();
	}
	
    public function markAs() {
		$objectArray = $this->input->post('objectArray');
		$marktype = $this->input->post('marktype');
		
		if (!$objectArray) $objectArray[] = $this->input->post('object');
		
		foreach ( $objectArray as $object ) {
			
			$objectParts = explode('-', $object);
			
			if ( count($objectParts) == 2 ) {
				$objectType = $objectParts[0];
				$objectId = $objectParts[1];
				
				switch($objectType) {
					case 'activity':
						$this->load->model('activitymodel');
						
						$activity = $this->activitymodel->getFullDataForActivity($objectId);
						
						
						if (!$activity->completion && $marktype == 'complete') {
							$this->activitymodel->markCompleted($objectId);
							
							$activity = $this->activitymodel->getFullDataForActivity($objectId);
							
							//store timesheet data for completion mark
							
							$tsdata = null;
							$tsdata->dateapplicable = date('Y-m-d');
							$tsdata->notbillable = 1;
							
							$tsdata->notes = $activity->activity_title . " Set as Complete by ".$this->authentication->getUserFullName();
							$tsdata->companyid = $activity->companyid;
							$tsdata->jobid = $activity->jobid;
							
							if ($activity->deadline) $tsdata->update_type = 'deadline';
							else if ($activity->milestone) $tsdata->update_type = 'milestone';
							else $tsdata->update_type = 'task';
							
							$tsdata->creatorid = $this->authentication->getUserId();
							$tsdata->datecreated = date('Y-m-d H:i:s');    	
							
							$this->load->model('timesheetmodel');
							
							$tsid = $this->timesheetmodel->add($tsdata);
						} else if ($activity->completion && $marktype == 'notcomplete') {
							$this->activitymodel->markNotCompleted($objectId);
							
							$activity = $this->activitymodel->getFullDataForActivity($objectId);
							
							//store timesheet data for completion mark
							
							$tsdata = null;
							$tsdata->dateapplicable = date('Y-m-d');
							$tsdata->notbillable = 1;
							
							$tsdata->notes = $activity->activity_title . " Set as Not Complete by ".$this->authentication->getUserFullName();
							$tsdata->companyid = $activity->companyid;
							$tsdata->jobid = $activity->jobid;
							
							if ($activity->deadline) $tsdata->update_type = 'deadline';
							else if ($activity->milestone) $tsdata->update_type = 'milestone';
							else $tsdata->update_type = 'task';
							
							$tsdata->creatorid = $this->authentication->getUserId();
							$tsdata->datecreated = date('Y-m-d H:i:s');    	
							
							$this->load->model('timesheetmodel');
							
							$tsid = $this->timesheetmodel->add($tsdata);
						}
						
						$this->load->library('notifications');
						$this->notifications->sendNotification($tsid);
					break;
					case 'timesheet':
						$this->load->model('timesheetmodel');
						
						if ($marktype == 'dismiss') $this->timesheetmodel->markDismissed($this->authentication->getUserId(), $objectId);
						if ($marktype == 'recall') $this->timesheetmodel->markNotDismissed($this->authentication->getUserId(), $objectId);
					break;
				}
			}
		}
    	echo 1;die();
    }
    
    public function setField($special = 0) {
    	$this->load->model('basemodel');
    	
    	$elementid = $this->input->post('element_id');
    	$newvalue = $this->input->post('update_value', false);
    	$origvalue = $this->input->post('original_html');
    	
    	$elementparts = explode('|', $elementid);

    	if (count($elementparts) >= 3) {
	    	$dataid = $elementparts[0];
	    	$datatype = $elementparts[1];
	    	$datafield = $elementparts[2];
	    	
	    	//make any modifications to data for mysql
	    	if ($special && $special == 'date') {
	    		
	    		if (strlen($newvalue)) {					
					$dateParts = explode('/', $newvalue);
					$savevalue	= date('Y-m-d', mktime(0, 0, 0, $dateParts[1], $dateParts[0], $dateParts[2]) );
	    		} else $savevalue = '';
	    		
	    	} else $savevalue = $newvalue;
	    	
	    	$this->basemodel->setModel($datatype);
	    	$this->basemodel->updateField($dataid, $datafield, $savevalue);
    		
	    	
	    	//output data in required format
	    	if ($special && $special == 'yesno') {
				if ($newvalue == 1) echo 'Yes';
				else echo 'No';
    		} else if ($special && $special == 'livestatus') {
				if ($newvalue == 1) echo 'Archived';
				else echo 'Live';
    		} else if ($special && ($special == 'select' || $special == 'supplierselect')) {
    			//this is a select element, must return the value of the item
				$foreignTable = $elementparts[3];
				$foreignField = $elementparts[4];
				
				$this->basemodel->setModel($foreignTable);
				$itemDetails = $this->basemodel->retrieve_by_pkey($newvalue);
				
				echo $itemDetails->$foreignField;
			} else if ($special &&  $special == 'contactselect') {
    			//this is a select element, must return the value of the item
				$this->load->model('contactmodel');

				if ($newvalue) {
					$itemDetails = $this->contactmodel->retrieve_by_pkey($newvalue);
					echo $itemDetails->firstname.' '.$itemDetails->surname;
				} else {
					echo "None assigned";
				}
				
    		} else if ($special &&  $special == 'userselect') {
    			//this is a select element, must return the value of the item
				$this->load->model('usersmodel');

				$itemDetails = $this->usersmodel->retrieve_by_pkey($newvalue);
				
				echo $itemDetails->firstname.' '.$itemDetails->lastname;
    		} else if ($special &&  $special == 'countryselect') {
    			//this is a select element, must return the value of the item
				$this->basemodel->setModel('country');

				$itemDetails = $this->basemodel->retrieve_by_pkey($newvalue);
				
				echo $itemDetails->printable_name;
			} else echo ucfirst(nl2br($newvalue));
    		
    	} else echo $origvalue; // output original value as we seem to have had a problem
    }
    
	public function addField_ajax() {
    	$this->load->model('basemodel');
    	$this->load->model('friendly_urlsmodel');

    	$fieldname = $this->input->post('field', TRUE);
    	$contenttype = $this->input->post('contenttype', TRUE);
    	$value = $this->input->post('value', TRUE);
    	
    	$this->basemodel->setModel($contenttype);
    	
    	if ( !$this->basemodel->find(array($fieldname => $value)) ) {    	
			$newid = $this->basemodel->add(array($fieldname => $value));
			
			//create furl for item.
			$friendly_url_data = array();
			$friendly_url_data['friendly_url'] = url_title($value);
			$friendly_url_data['content_type'] = $contenttype;
			$friendly_url_data['contentid'] = $newid;
			
			$fieldid = $this->friendly_urlsmodel->add($friendly_url_data);
	
			echo($newid);
		
		} else echo 0;
		
		die();
    }

	//checks if the current session user is logged in.
    protected function _checkAuthentication() {
    	if (!$this->authentication->isLoggedIn()) redirect('cerberus/login', 'refresh');
    }

}
?>
